package com.zxjbyte.yiyi.module.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zxjbyte.yiyi.framework.common.domain.api.PageResult;
import com.zxjbyte.yiyi.framework.common.enums.CommonEnum;
import com.zxjbyte.yiyi.framework.common.util.CollXUtil;
import com.zxjbyte.yiyi.framework.mybatis.service.impl.BaseServiceXImpl;
import com.zxjbyte.yiyi.framework.mybatis.util.Condition;
import com.zxjbyte.yiyi.framework.mybatis.util.UniqueChecker;
import com.zxjbyte.yiyi.module.system.domain.entity.DevConfigPO;
import com.zxjbyte.yiyi.module.system.domain.param.DevConfigAddParam;
import com.zxjbyte.yiyi.module.system.domain.param.DevConfigListParam;
import com.zxjbyte.yiyi.module.system.domain.param.DevConfigUpdateParam;
import com.zxjbyte.yiyi.module.system.domain.vo.DevConfigVO;
import com.zxjbyte.yiyi.module.system.enums.DevConfigCategoryEnum;
import com.zxjbyte.yiyi.module.system.enums.DevConfigKeyEnum;
import com.zxjbyte.yiyi.module.system.enums.DictCodeEnum;
import com.zxjbyte.yiyi.module.system.mapper.DevConfigMapper;
import com.zxjbyte.yiyi.module.system.service.DevConfigService;
import com.zxjbyte.yiyi.module.system.util.cache.DevConfigCacheUtil;
import com.zxjbyte.yiyi.module.system.util.cache.DictCacheUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import static com.zxjbyte.yiyi.framework.common.enums.SortOrder.DESC;
import static com.zxjbyte.yiyi.framework.common.util.ValidationUtil.*;

/**
 * @Author zhangxingjia
 * @Date 2024/9/12 16:32
 * @Version: 1.0
 */
@Service
public class DevConfigServiceImpl extends BaseServiceXImpl<DevConfigMapper, DevConfigPO> implements DevConfigService {

    @Override
    public PageResult<DevConfigVO> list(DevConfigListParam param) {
        LambdaQueryWrapper<DevConfigPO> wrapper = Wrappers.<DevConfigPO>lambdaQuery()
                .eq(Objects.nonNull(param.getCategory()), DevConfigPO::getCategory, param.getCategory())
                .ge(Objects.nonNull(param.getStartTime()), DevConfigPO::getCreateTime, param.getStartTime())
                .le(Objects.nonNull(param.getEndTime()), DevConfigPO::getCreateTime, param.getEndTime())
                .like(Objects.nonNull(param.getConfigKey()), DevConfigPO::getConfigKey, param.getConfigKey());
        IPage<DevConfigPO> pageResult = page(Condition.getPage(param, DevConfigPO::getCreateTime, DESC), wrapper);
        List<DevConfigPO> records = pageResult.getRecords();
        List<DevConfigVO> voList = null;
        if(CollXUtil.isNotEmpty(records)){
            voList = CglibUtil.copyList(records, DevConfigVO::new);
        }
        return PageResult.of(voList, pageResult);
    }

    @Override
    public DevConfigVO detail(Long id) {
        DevConfigPO devConfigPo = getById(id);
        assertNotNull(devConfigPo, () -> "查询配置详情数据异常！");
        return CglibUtil.copy(devConfigPo, DevConfigVO.class);
    }

    @Override
    public void addDevConfig(DevConfigAddParam param) {
        checkParam(param.getCategory());
        checkDevConfig(null, param.getConfigKey());
        DevConfigPO entity = new DevConfigPO();
        entity.setCategory(StrUtil.blankToDefault(param.getCategory(), DevConfigCategoryEnum.BIZ_DEFINE.getCode()));
        entity.setConfigKey(param.getConfigKey());
        entity.setConfigValue(param.getConfigValue());
        entity.setRemark(param.getRemark());
        save(entity);
        // 添加缓存
        DevConfigCacheUtil.put(param.getConfigKey(), param.getConfigValue());
    }

    @Override
    public void updateDevConfig(DevConfigUpdateParam param) {
        checkParam(param.getCategory());
        DevConfigPO devConfigPo = checkDevConfig(param.getId(), param.getConfigKey());
        devConfigPo.setConfigKey(param.getConfigKey());
        devConfigPo.setConfigValue(param.getConfigValue());
        devConfigPo.setCategory(param.getCategory());
        devConfigPo.setRemark(StrUtil.nullToEmpty(param.getRemark()));
        updateById(devConfigPo);
        DevConfigCacheUtil.remove(devConfigPo.getConfigKey());
    }

    @Override
    public void deleteDevConfig(Long id) {
        DevConfigPO devConfigPo = getById(id);
        assertNotNull(devConfigPo, () -> "配置不存在");
        assertFalse(CommonEnum.contain(DevConfigKeyEnum.class, devConfigPo.getConfigKey()), "内置系统配置键不可删除");
        if(removeById(devConfigPo)){
            DevConfigCacheUtil.remove(devConfigPo.getConfigKey());
        }
    }

    @Override
    public DevConfigPO getByConfigKey(String configKey) {
        return lambdaQuery().eq(DevConfigPO::getConfigKey, configKey).last("limit 1").one();
    }


    private void checkParam(String category){
        assertFalse(StrUtil.isNotEmpty(category) && !DictCacheUtil.getDictItemValueAsString(DictCodeEnum.DEV_CONFIG_CATEGORY).contains(category), "请选择正确的类别！");
    }

    private DevConfigPO checkDevConfig(Long id, String configKey){
        DevConfigPO devConfigPo = null;
        if(id != null){
            assertNotNull((devConfigPo = getById(id)), () -> "系统配置不存在");
            assertFalse(Objects.equals(DevConfigCategoryEnum.SYSTEM_BASE.getCode(), devConfigPo.getCategory())
                    && !Objects.equals(devConfigPo.getConfigKey(), configKey), "内置系统配置键不可修改！");
        }
        assertTrue(UniqueChecker.of(this).where(DevConfigPO::getConfigKey, configKey).ignoreId(id).check(), "存在重复的配置键，重复键为：{}", configKey);
        return devConfigPo;
    }
}
